<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Web Push Notification</title>
  </head>
  <body>
    <button id="subscribeButton">订阅推送</button>
    <button id="sendTestNotification">发送测试通知</button>
    <script>
      // 检查浏览器是否支持 Service Worker 和 Notification
      if ("serviceWorker" in navigator && "Notification" in window) {
        // 注册 Service Worker
        navigator.serviceWorker
          .register("/service-worker.js")
          .then((registration) => {
            console.log("Service Worker 注册成功:", registration);
          })
          .catch((error) => {
            console.error("Service Worker 注册失败:", error);
          });
      }

      const subscribeButton = document.getElementById("subscribeButton");
      subscribeButton.addEventListener("click", async () => {
        // 请求通知权限
        const permission = await Notification.requestPermission();
        if (permission === "granted") {
          console.log("通知权限已授予");
          // 这里可以添加订阅推送服务的逻辑
        } else {
          console.log("通知权限被拒绝");
        }
      });

      const sendTestNotificationButton = document.getElementById(
        "sendTestNotification"
      );

      sendTestNotificationButton.addEventListener("click", async () => {
        if (Notification.permission !== "granted") {
          console.log("请先获取通知权限");
          return;
        }
        navigator.serviceWorker.getRegistration().then(function (registration) {
          if (registration && registration.active) {
            // 模拟推送事件
            registration.active.postMessage({
              type: "push",
              data: "你好世界",
            });
          } else {
            console.log("Service Worker 未激活");
          }
        });
      });
      setInterval(() => {
        sendTestNotificationButton.click(); // 模拟点击发送测试通知按钮
      }, 5000);
    </script>
  </body>
</html>
